package cn.iocoder.yudao.module.system.controller.admin.auth;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.config.SecurityProperties;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginReqVO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthPermissionInfoRespVO;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.portal.PortalUserDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.service.auth.PortalAuthService;
import cn.iocoder.yudao.module.system.service.portal.PortalUserService;
import cn.iocoder.yudao.module.system.util.HttpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getPortalLoginUserId;

@Tag(name = "门户网站 - 认证")
@RestController
@RequestMapping("/system/portal/auth")
@Validated
@Slf4j
public class PortalAuthController {

    @Resource
    private PortalAuthService authService;

    @Resource
    private SecurityProperties securityProperties;

    @Resource
    private PortalUserService userService;

    @Resource
    private HttpUtil httpUtil;

    /**
     * 账号密码登录（核心功能）
     */
    @PostMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public CommonResult<AuthLoginRespVO> login(@RequestBody @Valid AuthLoginReqVO reqVO) {
        return success(authService.login(reqVO));
    }

    /**
     * 登出系统
     */
    @PostMapping("/logout")
    @PermitAll
    @Operation(summary = "登出系统")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        // 从请求头/参数中获取令牌
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
        if (StrUtil.isNotBlank(token)) {
            authService.logout(token, LoginLogTypeEnum.LOGOUT_SELF.getType());
        }
        return success(true);
    }
    @GetMapping("/get-permission-info")
    @PermitAll
    @Operation(summary = "获取登录用户的权限信息")
    public CommonResult<PortalUserDO> getPermissionInfo() {
        if (getPortalLoginUserId() == null){
            return CommonResult.error(ErrorCodeConstants.AUTH_REFRESH_TOKEN_INVALID);
        }
        // 1.1 获得用户信息
        PortalUserDO user = userService.getUser(getPortalLoginUserId());
        if (user == null){
            return CommonResult.error(ErrorCodeConstants.AUTH_PORTAL_USER_NOT_EXISTS);
        }
        //删除密码
        user.setPassword(null);
        if (user == null) {
            return success(null);
        }
        // 2. 拼接结果返回
        return success(user);
    }

    /**
     * 刷新令牌（当accessToken过期时使用）
     */
    @PostMapping("/refresh-token")
    @PermitAll
    @Operation(summary = "刷新令牌")
    @Parameter(name = "refreshToken", description = "刷新令牌", required = true)
    public CommonResult<AuthLoginRespVO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return success(authService.refreshToken(refreshToken));
    }


    /**
     * 用户鉴权接口
     *
     */
    @PostMapping("/authenticate")
    @PermitAll
    @Operation(summary = "用户鉴权接口")
    public CommonResult authenticate(@RequestParam("username") String username,@RequestParam("password") String password) throws UnsupportedEncodingException {
        // 先解码（处理被编码的字符如 %2B、%2F 等）
        String decodedPassword = URLDecoder.decode(password, StandardCharsets.UTF_8.name());
        // 再修复可能被解析为空格的 + 号
        String correctedPassword = decodedPassword.replace(" ", "+");

        return success(authService.identityAuthenticate(username, correctedPassword));
    }


    /**
     * 单点登录接口
     *
     */
    @GetMapping("/sso")
    @PermitAll
    @Operation(summary = "单点登录接口")
    public CommonResult<AuthLoginRespVO> sso(@RequestParam("tokenId") String tokenId,@RequestParam("pv") String pv,@RequestParam("cs") String cs) {
        return success(httpUtil.sendPost(tokenId,cs));
    }

}
    